import hilog from '@ohos.hilog';
import utils from '../core/utils';
import { XLog, LogLevel, OhPrinter, FilePrinter, LogConfiguration, DateFileNameGenerator, FileSizeBackupStrategy, FileLastModifiedCleanStrategy, ConsolePrinter } from '@ohos-port/xlog-ts';

class logger {
  private readonly domain: number;
  private readonly prefix: string;
  private readonly format: string = '%{public}s, %{public}s';

  constructor() {
    this.domain = 0xFF00;
    this.prefix = 'bilibili_ohos';
  }

  public init(filesDir: string) {
    try {
      let config = new LogConfiguration.Builder()
        .setTag(this.prefix)
        .setLogLevel(LogLevel.ALl)
        .build();
      let printer = new FilePrinter.Builder(`${filesDir}/logs`)
        .setFileNameGenerator(new DateFileNameGenerator())
        .setBackupStrategy(new FileSizeBackupStrategy(5 * 1024 * 1024))
        .setCleanStrategy(new FileLastModifiedCleanStrategy(7 * 24 * 60 * 60 * 1000))
        .build();
      XLog.init(config, [printer, new OhPrinter(), new ConsolePrinter()]);
    } catch (e) {
      hilog.error(this.domain, this.prefix, this.format, e);
    }
  }

  public info(msg: string, show?: boolean) {
    try {
      hilog.info(this.domain, this.prefix, this.format, msg);
      XLog.i(msg);
      if (show)
        utils.showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }

  public error(e: any, title?: string, show?: boolean) {
    try {
      let msg = typeof e === 'string' ? e : `error title: ${title ?? ''} / message: ${e?.message} / stack: ${e?.stack}`;
      hilog.error(this.domain, this.prefix, this.format, msg);
      XLog.e(msg);
      if (show)
        utils.showPopup('发生错误：' + msg);
    } catch (e) {
      console.log(e);
    }
  }
}
export default new logger();